
local Grid = require("bag.Grid")
local Msg = require("core.Msg")

local tb_dfs = {}
local tb_dfs_len = 0

local function fix_number(t)
	if type(t) == "number" then
		t = t - t % 0.001	-- 
		if -1 < t and t < 1 then
			return string.gsub(t, "0.", ".", 1)
		end
	end
	return t
end

local function is_empty_table(tb)
	for k, v in pairs(tb) do
		if tb[0] and tb[0] < k then
			break
		end
		if k ~= 0 then
			if type(v) == "table" then
				if not is_empty_table(v) then
					return
				end
			else
				if v ~= 0 and v ~= "" then
					return
				end
			end
		end
	end
	return true
end

local function dfsMakeItem(s)
	local first
	local type_v
	for k, v in pairs(s) do
		if s[0] and s[0] < k then
			break
		end
		if type(v) == "table" and not is_empty_table(v) or type(v) ~= "table" and k ~= 0 and v ~= "" and v ~= 0 then
			if first then
				if type_v == "string" or type_v == "number" and type(k) == "number" then
					tb_dfs_len = tb_dfs_len + 1
					tb_dfs[tb_dfs_len] = ","
				end
			else
				first = true
			end
			tb_dfs_len = tb_dfs_len + 1
			tb_dfs[tb_dfs_len] = k
			if type(v) == "table" then
				tb_dfs_len = tb_dfs_len + 1
				tb_dfs[tb_dfs_len] = "{"
				dfsMakeItem(v)
				tb_dfs_len = tb_dfs_len + 1
				tb_dfs[tb_dfs_len] = "}"
			else
				tb_dfs_len = tb_dfs_len + 1
				tb_dfs[tb_dfs_len] = "="
				tb_dfs_len = tb_dfs_len + 1
				tb_dfs[tb_dfs_len] = fix_number(v)
			end
			type_v = type(v)
		end
	end
end

function tb2str(tb)
	tb_dfs_len = 0
	dfsMakeItem(tb)
	return table.concat(tb_dfs, nil, 1, tb_dfs_len)
end

function fontItem(grid, name)
	local msgRet = Msg.gc.GC_BAG_ITEM_CHANGE
	Grid.makeItem(grid, msgRet.itemData, 0)
	if name then
		msgRet.itemData.name = name
	end
	--print(#tb2str(msgRet.itemData), tb2str(msgRet.itemData))
	return tb2str(msgRet.itemData)
end

function fontFriend(db,type)
	local msgRet = Msg.gc.GC_FRIEND_UPDATE
	FriendLogic.makeFriend(msgRet.friend,db,-1,type)
	return tb2str(msgRet.friend)
end